package com.own.component.log.login.util;

import com.own.component.log.login.property.LogLoginProperty;
import com.own.component.log.login.property.LoginLimitRule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * LoginLimitRuleUtil
 *
 * @author chenxueli
 * @date 2023-12-13 09:17:00
 */
@Slf4j
@Component
public class LoginLimitRuleUtil {

    private static final Map<String, List<LoginLimitRule>> LOGIN_LIMIT_RULE_MAP = new HashMap<>();

    @Resource
    private LogLoginProperty logLoginProperty;

    @PostConstruct
    private void init() {
        LOGIN_LIMIT_RULE_MAP.clear();
        var map = logLoginProperty.getLimitRules();
        if (map == null) {
            return;
        }
        map.forEach((key, values) -> {
            LOGIN_LIMIT_RULE_MAP.put(key, values.stream().sorted(Comparator.comparing(LoginLimitRule::getMaxFailCount).reversed()).collect(Collectors.toList()));
        });
    }

    /**
     * 获取对应的规则信息
     *
     * @param type 类型
     * @return 规则信息
     */
    public List<LoginLimitRule> get(String type) {
        return LOGIN_LIMIT_RULE_MAP.get(type);
    }

}
